import React, { useState, useImperativeHandle, useRef, useMemo, useCallback } from 'react';
import { intl } from '@/utils';
import { Column, TreeList } from 'devextreme-react/tree-list';
import { getTplList, templateTree } from './service';
import { getCpasIcon } from '@/utils/icon';
import notify from 'devextreme/ui/notify';
import Popup from 'devextreme-react/popup';
import { CpasIcon } from '~/public/cpas-ui';
import AudDialog from '@/pages/components/Aud/AudDialog';

const TemplateDialog: React.FC<any> = React.forwardRef((props: any, ref) => {
  const [treeData, setTreeData] = useState<any[]>([]);
  const [tplList, setTplList] = useState<any[]>([]);
  const [defTplName, setDefTplName] = useState<string>('');
  const [visible, setVisible] = useState<boolean>(false);
  const diaParams = useRef<any>();
  const paperTreeViewRef = useRef<any>(null);

  const [sourcePath, setSourcePath] = useState<string>('');


  //选择一个模板名称
  const selectOneTempalte = async (mbmc: string) => {
    setSourcePath(mbmc);
    setDefTplName(mbmc);
    const res = await templateTree(mbmc);
    if (res.success) {
      setTreeData(res.data);
    } else {
      setTreeData([]);
    }
  };

  const fun_TplListData = async () => {
    const res = await getTplList();
    if (res.success) {
      if (res.data?.length) {
        setTplList(res.data);
        selectOneTempalte(res.data[0].mbmc);//选中第一个
      } else {
        setTplList([]);
      }
    }
  };

  // 自定义方法
  useImperativeHandle(ref, () => ({
    show: async (params: any) => {
      diaParams.current = params;
      await fun_TplListData();
      setVisible(true);
    },
    close: () => { setVisible(false) }
  }));
  const funCancel = () => {
    paperTreeViewRef.current?.instance.clearFilter('search');
    paperTreeViewRef.current?.instance?.clearSelection();
    setDefTplName('');
    setTreeData([]);
    setVisible(false);
  }

  return (
    <>
      <AudDialog
        visible={visible}
        title={diaParams.current?.args?.title}
        minWidth={520}
        width={720}
        height="80vh"
        {...props}
        showCancelButton={true}
        showOkButton={true}
        onHiding={() => {
          funCancel()
        }}
        onOK={() => {
          if (diaParams.current?.okCallback) {
            const treesjdgs = paperTreeViewRef.current?.instance.getSelectedRowsData("leavesOnly");
            if (treesjdgs?.length === 0) return notify('请选择底稿！', 'error', 2000);
            if (diaParams.current?.args?.isMultiple) {
              diaParams.current?.okCallback(treesjdgs, sourcePath);
            } else {
              let isJd = treesjdgs[0].id;
              diaParams.current?.okCallback(isJd, sourcePath);
            }
            funCancel();
          }
        }}
        onCancel={() => {
          funCancel();
        }}
      >
        {useMemo(() => {
          if (!visible) return <></>;
          return <TreeList
            className='PaperTreeList'
            id="tpl"
            dataSource={treeData}
            showRowLines={false}
            showBorders={true}
            columnAutoWidth={true}
            ref={paperTreeViewRef}
            width='100%'
            height='100%'
            searchPanel={{
              visible: true,
              width: 180,
              placeholder: ''
            }}
            toolbar={{
              items: [
                {
                  widget: 'dxSelectBox',
                  location: 'before',
                  options: {
                    width: 380,
                    value: defTplName,
                    dataSource: tplList,
                    searchEnabled: true,
                    searchMode: 'contains',
                    searchExpr: 'mbmc',
                    valueExpr: 'mbmc',
                    displayExpr: 'mbmc',
                    onValueChanged: (e: any) => {
                      selectOneTempalte(e.value);
                    }
                  }
                },
                {
                  name: 'searchPanel',
                  location: 'after',
                }
              ]
            }}
            keyExpr="id"
            parentIdExpr="pid"
            selection={
              diaParams.current?.args?.isMultiple ? {
                recursive: true,
                mode: 'multiple'
              } : {
                mode: 'single'
              }}
          >
            <Column
              dataField="id"
              caption="底稿名称"
              cellRender={(cell) => {
                const { data } = cell;
                return <div style={{ display: 'flex', justifyContent: 'left', alignItems: 'center' }}>
                  <span style={{ marginRight: "8px" }}>{getCpasIcon(data.dglx)}</span> {data.id}
                </div>
              }}
            />
          </TreeList>
        }, [treeData, visible])}

      </AudDialog>
    </>
  );
});

export default TemplateDialog